/**
 * 获取 blob
 * @param  {String} url 目标文件地址
 * @return {Promise} 
 */
export function getBlob(url) {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest()
    url = url + `?r=${Math.random()}`
    xhr.open("GET", url, true)
    xhr.responseType = "blob"
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response)
      }
    }

    xhr.send()
  })
}

/**
* 保存
* @param  {Blob} blob     
* @param  {String} fileName 想要保存的文件名称
* @param  {String} type 想要保存的文件名称
*/
export function downloadFileByBlob(data, fileName, type) {
  let options = {}
  if (type) {
    options = { type: `application/${type}` }
  }
  const blob = new Blob([data], options)
  if ("download" in document.createElement("a")) { // 非IE下载
    const alink = document.createElement("a")
    alink.download = fileName
    alink.style.display = "none"
    alink.href = URL.createObjectURL(blob)
    document.body.appendChild(alink)
    alink.click()
    URL.revokeObjectURL(alink.href) // 释放URL 对象
    document.body.removeChild(alink)
  } else { // IE10+下载
    navigator.msSaveBlob(blob, fileName)
  }
}

/**
* 下载
* @param  {String} url 目标文件地址
* @param  {String} filename 想要保存的文件名称
*/
export function downloadFileByUrl(url, filename, type) {
  getBlob(url).then(blob => {
    downloadFileByBlob(blob, filename, type)
  })
}